package com.binlog.core.container;

import com.binlog.config.BinLogDbProperty;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Clint container
 *
 * @description:
 * @author: chenyj
 * @date 2023 -10-13 17:18:20
 */
@Slf4j
public class ClintContainer {

    public static final Map<Long, BinaryLogClient> BINARY_LOG_CLIENT_MAP = new ConcurrentHashMap<>();
    public static final Map<Long, BinLogDbProperty> BINARY_LOG_PROPERTY_MAP = new ConcurrentHashMap<>();

    /**
     * 变更监听点 position
     * @param serviceId
     * @param positionId
     * @param binlogFileName
     */
    public static void changePosition(Long serviceId, Long positionId, String binlogFileName) {
        BinaryLogClient binaryLogClient = BINARY_LOG_CLIENT_MAP.get(serviceId);
        if (null == binaryLogClient) {
            return;
        }
        if (null == positionId || StringUtils.isEmpty(binlogFileName)) {
            return;
        }
        binaryLogClient.setBinlogPosition(positionId);
        binaryLogClient.setBinlogFilename(binlogFileName);
    }


    /**
     * 添加client
     * @param binaryLogClient
     * @param binLogDbProperty
     */
    public static void addClient(BinaryLogClient binaryLogClient, BinLogDbProperty binLogDbProperty) throws IOException {
        if (null == binaryLogClient) {
            return;
        }
        BINARY_LOG_CLIENT_MAP.putIfAbsent(binaryLogClient.getServerId(), binaryLogClient);
        BINARY_LOG_PROPERTY_MAP.putIfAbsent(binaryLogClient.getServerId(), binLogDbProperty);
        // 变更监听点
        changePosition(binaryLogClient.getServerId(), binLogDbProperty.getBinlogPosition(), binLogDbProperty.getBinlogFilename());
        // 启动
        log.info("add client:{}", binaryLogClient.getServerId());
        binaryLogClient.connect();
    }

    /**
     * 移除client
     */
    @SneakyThrows
    public static void removeClient(Long serviceId) {
        if (null == serviceId) {
            return;
        }
        BinaryLogClient binaryLogClient = BINARY_LOG_CLIENT_MAP.get(serviceId);
        BINARY_LOG_CLIENT_MAP.remove(serviceId);
        BINARY_LOG_PROPERTY_MAP.remove(serviceId);
        log.info("remove client:{}", serviceId);
        binaryLogClient.disconnect();
    }
}
